package com.atyjh.reggie.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.dto.UserDTO;
import com.atyjh.reggie.entity.Employee;
import com.atyjh.reggie.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import static com.atyjh.reggie.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.15
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        1、获取本次请求的URI
        String requestURI = request.getRequestURI();
//        2、判断本次请求是否需要处理
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
        };
        boolean check = check(requestURI, urls);
//        3、如果不需要处理，则直接放行
        if (check) {
            log.info("该请求不需要处理：{}", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//        4、判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute(LOGIN_USER_KEY) != null) {
            log.info("已经登录，该请求直接放行：{}", requestURI);
            UserDTO user = (UserDTO) request.getSession().getAttribute(LOGIN_USER_KEY);
            UserHolder.addUser(user);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//        5、如果未登录则返回未登录结果
        log.info("未登录，该请求被过滤：{}", requestURI);
        response.getWriter().write(JSONUtil.toJsonStr(Result.error("NOTLOGIN")));
    }

    private boolean check(String requestURI, String[] urls) {

//        hutools包内的工具类，实现ant风格的路径匹配
        AntPathMatcher antPathMatcher = new AntPathMatcher();

        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
